package org.springblade.modules.repair.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.common.constant.VoiceConstant;
import org.springblade.common.utils.AsyncHttpUtil;
import org.springblade.common.utils.autoid.annotation.AutoIdempotent;
import org.springblade.common.utils.autoid.service.TokenService;
import org.springblade.common.utils.mq.AlarmSend;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.repair.dto.plan.TlwRescuePlanChangeStateDTO;
import org.springblade.modules.repair.entity.Building;
import org.springblade.modules.repair.service.IMaintainPlanContentUserService;
import org.springblade.modules.repair.service.MaintainReportService;
import org.springblade.modules.repair.service.PlanHistoryImageService;
import org.springblade.modules.repair.service.WeChatDialogueService;
import org.springblade.modules.resource.utils.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;

/**
 * @author Jackey
 * @date 2021年08月18日 11:00 上午
 */
@RestController
@RequestMapping("/test")
@Api(value = "测试接口", tags = "测试接口")
public class TestController {
  private static final Logger log = LoggerFactory.getLogger(TestController.class);
  @Autowired
  TokenService tokenService;
  @Autowired
  WeChatDialogueService weChatDialogueService;

  @Autowired
  AlarmSend alarmSend;
  @Autowired
  private IMaintainPlanContentUserService planContentUserService;

  @Autowired
  private PlanHistoryImageService planHistoryImageService;

  @Autowired
  private MaintainReportService maintainReportService;

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @GetMapping("/createToken")
  public R<String> createTOken() {
    return R.data(tokenService.createToken());
  }

  @GetMapping("/ping")
  public R<Boolean> ping() {
    return R.status(true);
  }

  @GetMapping("/testErrorCode")
  public R<Boolean> testErrorCode() {
    int i = 1 / 0;
    return R.status(true);
  }

  @AutoIdempotent
  @PostMapping("/test_post")
  public R<Boolean> testPost(@RequestBody Building building) {
    System.out.println(building);
    return R.status(true);
  }

  /**
   * 延迟队列
   */
  @GetMapping("/mq")
  public R<Boolean> delayedMessage() {
    Date signDate = new Date();
    // long deliverTime = DateUtil.millisecond(signDate) + 60000;
    long date = System.currentTimeMillis() + 10000;
    alarmSend.sendWxPartsPlanSignOutDelayed(date, "test");
    return R.status(Boolean.TRUE);
  }

  /**
   * 公众号模板消息
   *
   * @return
   */
  @GetMapping("/template")
  public R<Boolean> testTemplateMessage() {
    Map<String, String> templateDataMap = new HashMap<>(5);
    // 必要参数
    templateDataMap.put("first", "first");
    templateDataMap.put("keyword1", "keyword1");
    templateDataMap.put("keyword2", DateUtil.formatDateTime(new Date()));
    templateDataMap.put("keyword3", "keyword3");
    // 必要参数
    templateDataMap.put("remark", "remark");

    return R.status(weChatDialogueService.sendMsg("o_9OJ51nkUn34dizEAjSz0HLbQrI",
        "erTDWzAL1vHYf_cE1f2yOzwpOCCKi4M0QswMlsUvht8", templateDataMap));
  }

  /**
   * 短信发送
   */
  @GetMapping("/sms")
  public R<Boolean> smsMessage() {
    Map<String, String> map = new HashMap<>();
    map.put("auditStatus", "【已受理】");

    return R.status(
        SmsUtil.sendMessage("maintenance_people", BladeConstant.ADMIN_TENANT_ID, map, "13422801411").isSuccess());
  }

  /**
   * 更新工单计划人及实际人
   *
   * @return
   */
  @TenantIgnore
  @GetMapping("/change/all/plan/user")
  public R<?> changeAllPlanUser() {
    return R.status(planContentUserService.changeAllPlanUser());
  }

  @Autowired
  private AsyncHttpUtil asyncHttpUtil;
  @Autowired
  private ProjectApiConfiguration projectApiConfiguration;

  @PostMapping("mqSendTest")
  public R mqSendTest() {
    Map<String, String> map = new HashMap<>(2);
    map.put("test", "123456");
    asyncHttpUtil.createPost(projectApiConfiguration.getWeb() + "/admin/mq/message/sendMessage",
        JSONObject.toJSONString(map), WebUtil.getRequest());
    return R.status(true);
  }

  /**
   * 短信发送
   */
  @GetMapping("/sendPhone")
  @ApiOperation("测试发送语音")
  public R<Boolean> sendPhone() {
    // Map<String, String> phoneMap = new HashMap<>(2);
    // phoneMap.put("place", "测试");
    // phoneMap.put("location", "梯无忧小程序");
    // phoneMap.put("phone", "13798824306");
    // phoneMap.put("templateCode", VoiceConstant.PARTS_MESSAGE);
    // asyncHttpUtil.createPost(projectApiConfiguration.getWeb()+"/admin/voice/sendPhone",
    // JSONObject.toJSONString(phoneMap));

    planContentUserService.updateRescuePlanUserSignInfo(1914232542463004673L);
    return R.data(true);
  }

  @TenantIgnore
  @PostMapping("/rescue/plan/change/state")
  @ApiOperation(value = "救援工单-更新工单状态")
  public R<Boolean> rescuePlanChangeState(@RequestBody TlwRescuePlanChangeStateDTO param) {
    asyncHttpUtil.createPost(projectApiConfiguration.getWeb() + "/estate/tlw/screen/rescue/plan/change/state",
        Func.toJson(param), WebUtil.getRequest());
    return R.data(Boolean.TRUE);
  }

  @GetMapping("/druid")
  public void testDruid() {

  }

  @GetMapping("/test/tenant")
  public R<Boolean> testTenantId() {
    String tenantId = AuthUtil.getTenantId();
    Boolean isTrue = tenantId.equals("592800");
    return R.data(isTrue);
  }

  @GetMapping("/ai/image")
  public R<Boolean> aiImage(Long planId) {
    return R.data(planHistoryImageService.removeByPlan(planId));
  }

  /**
   * 慢SQL查询测试接口
   * 执行一个包含SLEEP函数的查询，确保执行时间超过1秒
   * 用于测试慢SQL告警和数据库插入功能
   */
  @GetMapping("/slow-sql")
  @ApiOperation(value = "慢SQL查询测试", notes = "执行一个超过1秒的查询，测试慢SQL告警和blade_slow_sql_alert表插入功能")
  public R<List<Map<String, Object>>> slowSqlQuery() {
    long startTime = System.currentTimeMillis();

    try {
      System.out.println("===== 开始执行慢SQL测试 =====");
      System.out.println("当前接口: /api/blade-repair/test/slow-sql");
      System.out.println("预期执行时间: 约3秒");
      System.out.println("预期触发: 慢SQL告警 + blade_slow_sql_alert表插入");

      List<Map<String, Object>> result = maintainReportService.executeSlowQuery();
      long endTime = System.currentTimeMillis();
      long executionTime = endTime - startTime;

      System.out.println("===== 慢SQL查询执行完成 =====");
      System.out.println("实际执行耗时: " + executionTime + "ms");
      System.out.println("查询结果条数: " + (result != null ? result.size() : 0));

      if (executionTime > 1000) {
        System.out.println("✅ 执行时间超过1秒，应该触发慢SQL告警和数据库插入");
      } else {
        System.out.println("⚠️ 执行时间未超过1秒，可能不会触发慢SQL告警");
      }

      System.out.println("请检查:");
      System.out.println("1. 控制台是否有P6Spy相关的慢SQL日志输出");
      System.out.println("2. 是否收到飞书告警消息");
      System.out.println("3. blade_slow_sql_alert表中是否有新插入的记录");
      System.out.println("====================================");

      return R.data(result, "慢SQL测试执行成功，耗时: " + executionTime + "ms");
    } catch (Exception e) {
      long endTime = System.currentTimeMillis();
      long executionTime = endTime - startTime;

      System.err.println("===== 慢SQL查询执行失败 =====");
      System.err.println("执行耗时: " + executionTime + "ms");
      System.err.println("错误信息: " + e.getMessage());
      System.err.println("====================================");

      e.printStackTrace();

      return R.fail("慢SQL查询执行失败: " + e.getMessage());
    }
  }

}
